package com.agileai.bpm.controller.define;

import java.util.ArrayList;
import java.util.List;

import com.agileai.bpm.bizmoduler.define.WfProcessManage;
import com.agileai.bpm.controller.emulation.ProcessHelper;
import com.agileai.bpm.model.ActivitiesDocument.Activities;
import com.agileai.bpm.model.ProcessDefineDocument;
import com.agileai.bpm.model.WatchActivityType;
import com.agileai.bpm.webservice.BPMService;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.renders.DispatchRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;

public class WfWatchActivitySelectHandler extends WfProcessInfoHandler{
	public WfWatchActivitySelectHandler(){
		super();
	}
	
	public ViewRenderer prepareDisplay(DataParam param){
		BPMService bpmService = ProcessHelper.instance().getBPMService();
		String processCode = param.get("processCode");
		String processId = bpmService.getCurrentProcessId(processCode);
		DataParam queryParam = new DataParam("WFP_ID",processId);
		WfProcessManage processManage = this.lookupService(WfProcessManage.class);
		DataRow row = processManage.getRecord(queryParam);
		String processDefineXML = row.getString("WFP_DEFINE");
		try {
			ProcessDefineDocument processDefineDocument = ProcessDefineDocument.Factory.parse(processDefineXML);
			Activities activities = processDefineDocument.getProcessDefine().getActivities();
			List<DataRow> processVars = null;
			if (activities != null){
				processVars = buildWatchActvities(activities);
			}
			this.setRsList(processVars);
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		
		return new LocalRenderer(getPage());
	}
	
	private List<DataRow> buildWatchActvities(Activities activities){
		List<DataRow> result = new ArrayList<DataRow>();
		WatchActivityType[] watchActivityTypes = activities.getWatchActivityArray();
		if (watchActivityTypes != null){
			for (int i=0; i< watchActivityTypes.length;i++){
				WatchActivityType forkActivityType = watchActivityTypes[i];
				DataRow row = new DataRow();
				row.put("ACTIVITY_NAME",forkActivityType.getName());
				row.put("ACTIVITY_CODE",forkActivityType.getCode());
				row.put("ACTIVITY_ID",forkActivityType.getId());
				result.add(row);
			}
		}
		return result;
	}
	
	public ViewRenderer doSelectAction(DataParam param){
		return new DispatchRenderer(getHandlerURL(WfProcessInvokerEditHandler.class));
	}
	public ViewRenderer doBackAction(DataParam param){
		return new DispatchRenderer(getHandlerURL(WfProcessInvokerEditHandler.class));
	}	
}
